package com.ssh.api.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.util.ServletContextAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.ssh.common.log.LogFactory;
import com.ssh.common.log.LogName;
import com.ssh.common.util.JsonResult;
import com.ssh.entity.ActivityImage;
import com.ssh.entity.ActivitySuperMarket;
import com.ssh.entity.SuperMarket;
import com.ssh.entity.SuperMarketProduct;
import com.ssh.entity.TaskBrand;
import com.ssh.entity.TaskImage;
import com.ssh.manager.ActivityImageManager;
import com.ssh.manager.SuperMarketManager;
import com.ssh.manager.TaskImageManager;
import com.sun.org.apache.bcel.internal.generic.NEW;
@Controller
@ParentPackage("client")
@Scope("prototype")
public class UploadImageClientAction extends ActionSupport implements ServletContextAware{
	private static final long serialVersionUID = 970773022382019911L;
	JsonResult jr=new JsonResult();
	private ServletContext servletContext;
	private long taskId;
    private long brandId;
    private long superMarketId;
    private int  imgType;
    private ActivitySuperMarket activitySuperMarket;


	private File[] upload;
    @SuppressWarnings("unused")
	private String[] uploadContentType;
    private String[] uploadFileName;
    
	@Resource(name="superMarketManagerImpl")
	private SuperMarketManager superMarketManager;
	@Resource(name="taskImageManagerImpl")
	private TaskImageManager taskImageManager;
	@Resource(name="activityImageManagerImpl")
	private ActivityImageManager activityImageManager;
	

	@Action(value ="uploadTaskImage",
			interceptorRefs = {
			@InterceptorRef(value = "fileUpload",params={"maximumSize","1024000","allowedTypes","image/bmp,image/png,image/gif,image/jpeg,image/jpg"}),
			@InterceptorRef(value = "basicStack")},
			results = {@Result(name = "uploadTaskImage",type="json",params={"root","jr","includeProperties","data\\[\\d+\\]\\.id"})}) 		
	public  String uploadTaskImage(){
		jr.setMethod("uploadTaskImage");
		 File[] files=this.upload;
     	String separator=System.getProperty("file.separator");
     	 //以服务器的文件保存地址和原文件名建立上传文件输出流
    	String imagePath=(String)this.servletContext.getInitParameter("taskImage");
    	imagePath+=separator+"t"+taskId;
        File uploadFilePath = new File(imagePath);
        // 如果该目录不存在,则创建之
        if(uploadFilePath.exists() == false) {
           if(!uploadFilePath.mkdirs()){
        	  jr.setCode("-1");
			  jr.setMessage("无法创建文件夹");
			  return "uploadTaskImage";
           }
        } 
		 try{
	        for(int i=0;i<files.length;i++){
	        	FileOutputStream fos = new FileOutputStream(imagePath +separator+ this.uploadFileName[i]);
	            FileInputStream fis = new FileInputStream(files[i]);
	            byte[] buffer = new byte[1024];
	            int len = 0;
	            while ((len = fis.read(buffer)) > 0){
	                fos.write(buffer , 0 , len);
	            }
	        }
	        //保存数据
	        List<TaskImage> data=new ArrayList<TaskImage>();
	        TaskBrand taskBrand=taskImageManager.findTaskBrand(taskId, brandId);
	        SuperMarket superMarket=superMarketManager.getSuperMarketById(superMarketId);
	        for(int i=0;i<files.length;i++){
	        	TaskImage taskImage=new TaskImage();
	        	taskImage.setTaskBrand(taskBrand);
	        	taskImage.setSuperMarket(superMarket);
	        	taskImage.setCreateDate(new Timestamp(System.currentTimeMillis()));
	        	taskImage.setDel(0);
	        	taskImage.setImgType(imgType);
	        	taskImage.setUrl("t"+taskId+"_"+ this.uploadFileName[i]);
	        	//taskImage.setUrl(separator+"t"+taskId+separator+ this.uploadFileName[i]);
	        	data.add(taskImageManager.save(taskImage));
	        }
	        jr.setData(data);
	        jr.setCode("0");
	        
		 }catch(Exception e){
			 jr.setCode("-1");
			 jr.setMessage("图片上传失败");
			 LogFactory.getDefaultLog().error(e.getMessage(), LogName.API);
		 }
		return "uploadTaskImage";
    }
	
	
	
	@Action(value ="uploadActivityImage",
			interceptorRefs = {
			@InterceptorRef(value = "fileUpload",params={"maximumSize","1024000","allowedTypes","image/bmp,image/png,image/gif,image/jpeg,image/jpg"}),
			@InterceptorRef(value = "basicStack")},
			results = {@Result(name = "uploadActivityImage",type="json",params={"root","jr","includeProperties","data\\[\\d+\\]\\.id"})}) 		
	public  String uploadActivityImage(){
		jr.setMethod("uploadActivityImage");
		 File[] files=this.upload;
     	String separator=System.getProperty("file.separator");
     	 //以服务器的文件保存地址和原文件名建立上传文件输出流
    	String imagePath=(String)this.servletContext.getInitParameter("activityImage");
    	imagePath+=separator+"a"+activitySuperMarket.getId();
        File uploadFilePath = new File(imagePath);
        // 如果该目录不存在,则创建之
        if(uploadFilePath.exists() == false) {
           if(!uploadFilePath.mkdirs()){
        	  jr.setCode("-1");
			  jr.setMessage("无法创建文件夹");
			  return "uploadActivityImage";
           }
        } 
		 try{
	        for(int i=0;i<files.length;i++){
	        	FileOutputStream fos = new FileOutputStream(imagePath +separator+ this.uploadFileName[i]);
	            FileInputStream fis = new FileInputStream(files[i]);
	            byte[] buffer = new byte[1024];
	            int len = 0;
	            while ((len = fis.read(buffer)) > 0){
	                fos.write(buffer , 0 , len);
	            }
	        }
	        //保存数据
	        List<ActivityImage> data=new ArrayList<ActivityImage>();
	        ActivitySuperMarket activitySuperMarket_=activityImageManager.loadActivitySuperMarket(activitySuperMarket.getId());
	        activitySuperMarket_.setHaibao(activitySuperMarket.getHaibao());
	        activitySuperMarket_.setDuitou(activitySuperMarket.getDuitou());
	        activitySuperMarket_.setToutao(activitySuperMarket.getToutao());
	        activitySuperMarket_.setDuanjia(activitySuperMarket.getDuanjia());
	        activitySuperMarket_.setChenlie(activitySuperMarket.getChenlie());
	        activitySuperMarket=activityImageManager.saveActivitySuperMarket(activitySuperMarket_);
	        for(int i=0;i<files.length;i++){
	        	ActivityImage activityImage=new ActivityImage();
	        	activityImage.setCreateDate(new Timestamp(System.currentTimeMillis()));
	        	SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
	        	activityImage.setName(dateFormat.format(activityImage.getCreateDate())+"-"+(i+1));
	        	activityImage.setActivitySuperMarket(activitySuperMarket);
	        	activityImage.setImageType(imgType);
	        	activityImage.setUrl("a"+activitySuperMarket.getId()+"_"+ this.uploadFileName[i]);
	        	data.add(activityImageManager.saveActivityImage(activityImage));
	        }
	        jr.setData(data);
	        jr.setCode("0");
	        
		 }catch(Exception e){
			 jr.setCode("-1");
			 jr.setMessage("图片上传失败");
			 LogFactory.getDefaultLog().error(e.getMessage(), LogName.API);
		 }
		return "uploadActivityImage";
    }




	public JsonResult getJr() {
		return jr;
	}

	public void setJr(JsonResult jr) {
		this.jr = jr;
	}


	public void setUpload(File[] upload) {
		this.upload = upload;
	}


	public void setUploadContentType(String[] uploadContentType) {
		this.uploadContentType = uploadContentType;
	}


	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
  

    private String getSavePath() throws Exception 
    {
        return ServletActionContext.getRequest().getRealPath("/");
    }


	public void setTaskId(long taskId) {
		this.taskId = taskId;
	}


	public void setBrandId(long brandId) {
		this.brandId = brandId;
	}


	public void setSuperMarketId(long superMarketId) {
		this.superMarketId = superMarketId;
	}


	public void setImgType(int imgType) {
		this.imgType = imgType;
	}


	@Override
	public void setServletContext(ServletContext arg0) {
		 this.servletContext=arg0;
	}



	public void setActivitySuperMarket(ActivitySuperMarket activitySuperMarket) {
		this.activitySuperMarket = activitySuperMarket;
	}



	public ActivitySuperMarket getActivitySuperMarket() {
		return activitySuperMarket;
	}




}
